SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

CREATE PROC dbo.LongRunningProcs
(
	@Table			sysname,
	@Top			int 		= NULL,
	@Owner			sysname		= NULL,
	@LoginName		nvarchar(256)	= NULL,
	@HostName		nvarchar(256) 	= NULL,
	@ApplicationName	nvarchar(256) 	= NULL,
	@NTUserName 		nvarchar(256)	= NULL,
	@StartTime		datetime	= NULL,
	@EndTime		datetime	= NULL,
	@MinDuration		int		= NULL,
	@MaxDuration		int		= NULL,
	@Debug			bit		= 0
)
AS
BEGIN
	SET NOCOUNT ON
	
	DECLARE @SELECT nvarchar(25), @ColumnList nvarchar(250), @FROM nvarchar(150), @WHERE nvarchar(250), @ORDERBY nvarchar(250)

	SET @SELECT = 'SELECT ' + CASE WHEN @Top IS NULL OR @Top < 0 THEN 'TOP 150' ELSE 'TOP ' + LTRIM(CAST(@Top AS varchar)) END
	SET @ColumnList = ' TextData, CAST(Duration/1000. AS decimal(6, 2)) AS [Duration (in Seconds)], LoginName, NTUserName, HostName, ApplicationName, SPID, StartTime, EndTime'
	SET @FROM = ' FROM ' + QUOTENAME(COALESCE(@Owner, 'dbo')) + '.' + QUOTENAME(@Table)

	SET @WHERE = ' WHERE EventClass = 43'

	IF @LoginName IS NOT NULL
	BEGIN
		SET @WHERE = @WHERE + ' AND LoginName LIKE ' + QUOTENAME(@LoginName, '''')
	END

	IF @HostName IS NOT NULL
	BEGIN
		SET @WHERE = @WHERE + ' AND HostName LIKE ' + QUOTENAME(@HostName, '''')
	END

	IF @ApplicationName IS NOT NULL
	BEGIN
		SET @WHERE = @WHERE + ' AND ApplicationName LIKE ' + QUOTENAME(@ApplicationName, '''')
	END	

	IF @NTUserName IS NOT NULL
	BEGIN
		SET @WHERE = @WHERE + ' AND NTUserName LIKE ' + QUOTENAME(@NTUserName, '''')
	END	

	IF (@StartTime IS NOT NULL) AND (@EndTime IS NOT NULL)
	BEGIN
		SET @WHERE = @WHERE + ' AND StartTime BETWEEN ' + QUOTENAME(CONVERT(varchar, @StartTime, 109), '''') + ' AND ' + QUOTENAME(CONVERT(varchar, @EndTime, 109), '''')
	END
	ELSE IF @StartTime IS NOT NULL
	BEGIN
		SET @WHERE = @WHERE + ' AND StartTime >= ' + QUOTENAME(CONVERT(varchar, @StartTime, 109), '''') 
	END
	ELSE IF @EndTime IS NOT NULL
	BEGIN
		SET @WHERE = @WHERE + ' AND StartTime <= ' + QUOTENAME(CONVERT(varchar, @EndTime, 109), '''') 
	END

	IF (@MinDuration IS NOT NULL) AND (@MaxDuration IS NOT NULL)
	BEGIN
		SET @WHERE = @WHERE + ' AND Duration BETWEEN ' + CAST(@MinDuration * 1000 AS varchar) + ' AND ' + CAST(@MaxDuration * 1000 as varchar)
	END
	ELSE IF @MinDuration IS NOT NULL
	BEGIN
		SET @WHERE = @WHERE + ' AND Duration >= ' + CAST(@MinDuration * 1000 AS varchar)
	END
	ELSE IF @MaxDuration IS NOT NULL
	BEGIN
		SET @WHERE = @WHERE + ' AND Duration <= ' + CAST(@MaxDuration * 1000 AS varchar)
	END

	SET @ORDERBY = 'ORDER BY Duration DESC'

	IF @Debug = 1
	BEGIN
		SELECT @SELECT + char(13) + @ColumnList + char(13) + @FROM + char(13) + @WHERE + char(13) + @ORDERBY
	END
	
	EXEC(@SELECT + @ColumnList + @FROM + @WHERE + @ORDERBY)
	
END
GO
